import {handleSql} from '../../database/mysql/index.js'
import {unioformDateTransform} from '../../utils/index.js'



class usersModel {
    constructor() {
        this.tableName = 'users';
    }
    
    // 获取所有用户
    async getAllUsers() {
        const sql = `SELECT * FROM ${this.tableName}`;
        return await handleSql(sql);
    }
    
    // 根据用户名和密码获取用户
    async getUserByCredentials(username, password) {
        const sql = `SELECT * FROM ${this.tableName} 
                     WHERE userName = ? AND password = ?`
        let result =  await handleSql(sql,[username,password])
        return result[0]
    }

    // 根据用户名，手机号，或者用户id获取用户信息
    async getUserByUniqueIdentifier(identifier) {
        // identifier 可以是用户名、手机号或用户ID，或者它们的组合
        const {userId,userName,phone} = identifier;
        let tmpUserId = userId || '%'
        let tmpUserName = userName || '%'
        let tmpPhone = phone || '%'
        // 不定条件组合查询
        const sql = `SELECT * FROM ${this.tableName} 
                     WHERE   id LIKE  '${tmpUserId}' 
                             AND  userName LIKE '${tmpUserName}' 
                             AND  phone LIKE '${tmpPhone}'  `
        let result =  await handleSql(sql)                     
        return result[0]
    }


    // 更新用户信息   待完善
    async updateUser(id, userData) {
        let finalUserData = userData
        if(userData?.roles){
            finalUserData.roles = JSON.stringify(userData?.roles)
        }
        const sql = `UPDATE ${this.tableName} SET ? WHERE id = ?`
        let result = await handleSql(sql,[finalUserData,id])
        if(result.affectedRows = 1){
            return true
        }else{
            return false
        }
    }


   
    //新增用户
    async addUser(userData) {
        const {userName,password, phone,randomQuestion } = userData
        let date = unioformDateTransform(new Date())
        const sql = `INSERT 
                     INTO ${this.tableName}(userName, password, phone, randomQuestion, createTime) 
                     VALUES (?, ?, ?, ?, ?)`;
        let result =  await handleSql(sql, [userName,password, phone, JSON.stringify(randomQuestion), date]);
        if(result.affectedRows = 1){
            return true
        }else{
            return false
        }
    }
   

    /*
    // 删除用户
    async deleteUser(id) {
        const sql = `DELETE FROM ${this.tableName} WHERE id = ?`;
        return await handleSql(sql, [id]);
    }
    */
}

export default new usersModel();